package cn.appinfo.controller.developer;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

import cn.appinfo.pojo.AppCategory;
import cn.appinfo.pojo.AppInfo;
import cn.appinfo.pojo.AppVersion;
import cn.appinfo.pojo.DataDictionary;
import cn.appinfo.pojo.DevUser;
import cn.appinfo.pojo.Paging;
import cn.appinfo.service.appCategory.AppCategoryService;
import cn.appinfo.service.appVersion.AppVersionService;
import cn.appinfo.service.appinfo.AppInfoService;
import cn.appinfo.service.dataDictionary.DataDictionaryService;

@Controller
@RequestMapping("/dev/flatform/app")
public class AppController {
	
	@Resource
	private AppInfoService appInfoService;
	@Resource 
	private DataDictionaryService dataDictionaryService;
	@Resource 
	private AppCategoryService appCategoryService;
	@Resource
	private AppVersionService appVersionService;
	
	@RequestMapping("/list")
	public String list(Model model,HttpSession session,
			@RequestParam(value="SoftwareName",required=false)String SoftwareName,
			@RequestParam(value="FlatformId",required=false)String FlatformId,
			@RequestParam(value="CategoryLevel1",required=false)String CategoryLevel1,
			@RequestParam(value="CategoryLevel2",required=false)String CategoryLevel2,
			@RequestParam(value="CategoryLevel3",required=false)String CategoryLevel3,
			@RequestParam(value="pageIndex",required=false)String currentPageNo,
			@RequestParam(value="Status",required=false)String Status){
		List<AppCategory> categoryLevel1List = getCategoryLevel(0);
		List<AppCategory> categoryLevel2List = null;
		List<AppCategory> categoryLevel3List = null;
		List<DataDictionary> statusList=dataDictionaryService.getStatusList();
		int _FlatformId =0;
		if(FlatformId != null && FlatformId!=""){
			_FlatformId = Integer.parseInt(FlatformId);
		}
		int _categoryLevel1=0;
		if(CategoryLevel1 != null && CategoryLevel1 != ""){
			_categoryLevel1 = Integer.parseInt(CategoryLevel1);
			categoryLevel2List = getCategoryLevel(Integer.parseInt(CategoryLevel1));
		}
		int _categoryLevel2=0;
		if(CategoryLevel2 != null && CategoryLevel2 != ""){
			_categoryLevel2 = Integer.parseInt(CategoryLevel2);
			categoryLevel3List = getCategoryLevel(Integer.parseInt(CategoryLevel2));
		}
		int _categoryLevel3=0;
		if(CategoryLevel3 != null && CategoryLevel3 != ""){
			_categoryLevel3 = Integer.parseInt(CategoryLevel3);
		}
		int _status=0;
		if(Status != null && Status != ""){
			_status = Integer.parseInt(Status);
		}
		int _devId = ((DevUser)session.getAttribute("devUserSession")).getId();
		Paging page = new Paging();
		page.setPageSize(5);
		page.setTotalCount(appInfoService.appInfoCount2(SoftwareName,_FlatformId,_categoryLevel1,_categoryLevel2,_categoryLevel3,_status,_devId));
		if(currentPageNo == null){
			page.setCurrentPageNo(1);
		}else{
			page.setCurrentPageNo(Integer.parseInt(currentPageNo));
		}
		List<AppInfo> appinfo = appInfoService.getAppInfoList2((page.getCurrentPageNo()-1)*page.getPageSize(),page.getPageSize(),SoftwareName
				,_FlatformId,_categoryLevel1,_categoryLevel2,_categoryLevel3,_status,_devId);
		List<DataDictionary> dataDictionary = dataDictionaryService.getFlatFormList();
		model.addAttribute("appInfoList",appinfo);
		model.addAttribute("pages", page);
		model.addAttribute("flatFormList", dataDictionary);
		model.addAttribute("statusList",statusList);
		model.addAttribute("categoryLevel1List",categoryLevel1List);
		model.addAttribute("categoryLevel2List",categoryLevel2List);
		model.addAttribute("categoryLevel3List",categoryLevel3List);
		model.addAttribute("queryFlatformId", _FlatformId);
		model.addAttribute("querySoftwareName",SoftwareName);
		model.addAttribute("queryCategoryLevel1", _categoryLevel1);
		model.addAttribute("queryCategoryLevel2", _categoryLevel2);
		model.addAttribute("queryCategoryLevel3", _categoryLevel3);
		model.addAttribute("queryStatus", _status);
		return "developer/appinfolist";
	}
	
	private List<AppCategory> getCategoryLevel(int id){
		return appCategoryService.getCategoryLevel(id);
	}
	
	@RequestMapping(value="/categorylevellist.json",produces={"application/json;charset=utf-8"})
	@ResponseBody
	public Object categorylevellist(@RequestParam("pid") String id){
		List<AppCategory> appCategoryList = getCategoryLevel(Integer.parseInt(id));
		return JSON.toJSONString(appCategoryList);
	}
	
	@RequestMapping(value="/datadictionarylist.json",produces={"application/json;charset=utf-8"})
	@ResponseBody
	public Object datadictionarylist(){
		List<DataDictionary> dataDoictionaryist = dataDictionaryService.getFlatFormList();
		return JSON.toJSONString(dataDoictionaryist);
	}
	
	@RequestMapping("/appinfoadd")
	public String appinfoadd(){
		return "developer/appinfoadd";
	}
	
	@RequestMapping(value="/appinfoaddsave",method=RequestMethod.POST)
	public String appinfoaddsave(AppInfo appInfo,HttpSession session,HttpServletRequest request,
			@RequestParam(value="a_logoPicPath",required= false) MultipartFile attach){
		String logoPicPath =  null;
		String logoLocPath =  null;
		if(!attach.isEmpty()){
			String path = request.getSession().getServletContext().getRealPath("statics"+java.io.File.separator+"uploadfiles");
			String oldFileName = attach.getOriginalFilename();//原文件名
			String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
			int filesize = 500000;
			if(attach.getSize() > filesize){//上传大小不得超过 50k
				request.setAttribute("fileUploadError", "* 上传文件过大！");
				return "developer/appinfoadd";
            }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") 
			   ||prefix.equalsIgnoreCase("jepg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式
				 String fileName = appInfo.getAPKName() + ".jpg";//上传LOGO图片命名:apk名称.apk
				 File targetFile = new File(path,fileName);
				 if(!targetFile.exists()){
					 targetFile.mkdirs();
				 }
				 try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					request.setAttribute("fileUploadError", " * 上传失败！");
					return "developer/appinfoadd";
				} 
				 logoPicPath = request.getContextPath()+"/statics/uploadfiles/"+fileName;
				 logoLocPath = path+File.separator+fileName;
			}else{
				request.setAttribute("fileUploadError", "* 上传文件格式不正确！");
				return "developer/appinfoadd";
			}
		}
		appInfo.setCreatedBy(((DevUser)session.getAttribute("devUserSession")).getId());
		appInfo.setCreationDate(new Date());
		appInfo.setLogoPicPath(logoPicPath);
		appInfo.setLogoLocPath(logoLocPath);
		appInfo.setDevId(((DevUser)session.getAttribute("devUserSession")).getId());
		appInfo.setStatus(1);
		try {
			if(appInfoService.add(appInfo)){
				return "redirect:/dev/flatform/app/list";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "developer/appinfoadd";
	}
	
	@RequestMapping(value="/apkexist.json",produces={"application/json;charset=utf-8"})
	@ResponseBody
	public Object apkexist(@RequestParam("APKName")String APKName){
		String getAPKName = appInfoService.getAPKName(APKName);
		String data=null;
		if(APKName!=null && APKName!=""){
			if(getAPKName!=null && getAPKName != ""){
				data="exist";
			}else{
				data="noexist";
			}
		}else{
			data="empty";
		}
		return JSON.toJSONString(data);
	}
	
	@RequestMapping(value="/appversionadd")
	public String appversionadd(@RequestParam("id")String id,Model model){
		List<AppVersion> appVersionList = appVersionService.getappVersionList(id);
		model.addAttribute("appVersionList",appVersionList);
		model.addAttribute("appId", id);
		return "developer/appversionadd";
	}
	
	@RequestMapping(value="/addversionsave",method=RequestMethod.POST)
	public String addversionsave(AppVersion appVersion,HttpServletRequest request,HttpSession session,
			@RequestParam(value="a_downloadLink",required=false)MultipartFile attach){
		String downloadLink =  null;
		String apkLocPath = null;
		String apkFileName = null;
		if(!attach.isEmpty()){
			String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
			String oldFileName = attach.getOriginalFilename();//原文件名
			String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
			if(prefix.equalsIgnoreCase("apk")){//apk文件命名：apk名称+版本号+.apk
				 String apkName = null;
				 try {
					apkName = appInfoService.getAppInfo(appVersion.getAppId()).getAPKName();
				 } catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				 }
				 if(apkName == null || "".equals(apkName)){
					 return "redirect:/dev/flatform/app/appversionadd?id="+appVersion.getAppId()
							 +"&error=error1";
				 }
				 apkFileName = apkName + "-" +appVersion.getVersionNo() + ".apk";
				 File targetFile = new File(path,apkFileName);
				 if(!targetFile.exists()){
					 targetFile.mkdirs();
				 }
				 try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return "redirect:/dev/flatform/app/appversionadd?id="+appVersion.getAppId()
							 +"&error=error2";
				} 
				downloadLink = request.getContextPath()+"/statics/uploadfiles/"+apkFileName;
				apkLocPath = path+File.separator+apkFileName;
			}else{
				return "redirect:/dev/flatform/app/appversionadd?id="+appVersion.getAppId()
						 +"&error=error3";
			}
		}
		appVersion.setCreatedBy(((DevUser)session.getAttribute("devUserSession")).getId());
		appVersion.setCreationDate(new Date());
		appVersion.setDownloadLink(downloadLink);
		appVersion.setApkLocPath(apkLocPath);
		appVersion.setApkFileName(apkFileName);
		try {
			if(appVersionService.appsysadd(appVersion)){
				appInfoService.updateVersionId(appVersion.getAppId());
				return "redirect:/dev/flatform/app/list";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "redirect:/dev/flatform/app/appversionadd?id="+appVersion.getAppId();
	}
	
	@RequestMapping("/appversionmodify")
	public String appversionmodify(@RequestParam("vid")String vid,@RequestParam("aid")String aid,
			Model model){
		List<AppVersion> appVersionList = appVersionService.getappVersionList(aid);
		AppVersion appVersion = appVersionService.getAppVersion(Integer.parseInt(vid));
		model.addAttribute("appVersionList", appVersionList);
		model.addAttribute("appVersion", appVersion);
		return "developer/appversionmodify";
	}
	
	@RequestMapping("/appversionmodifysave")
	public String appversionmodifysave(AppVersion appVersion,HttpServletRequest request,HttpSession session,
			@RequestParam(value="attach",required=false)MultipartFile attach){
		String downloadLink =  null;
		String apkLocPath = null;
		String apkFileName = null;
		if(!attach.isEmpty()){
			String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
			String oldFileName = attach.getOriginalFilename();//原文件名
			String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
			if(prefix.equalsIgnoreCase("apk")){//apk文件命名：apk名称+版本号+.apk
				 String apkName = null;
				 try {
					apkName = appInfoService.getAppInfo(appVersion.getAppId()).getAPKName();
				 } catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				 }
				 if(apkName == null || "".equals(apkName)){
					 return "redirect:/dev/flatform/app/appversionmodify?vid="+appVersion.getId()
							 +"&aid="+appVersion.getAppId()
							 +"&error=error1";
				 }
				 apkFileName = apkName + "-" +appVersion.getVersionNo() + ".apk";
				 File targetFile = new File(path,apkFileName);
				 if(!targetFile.exists()){
					 targetFile.mkdirs();
				 }
				 try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return "redirect:/dev/flatform/app/appversionmodify?vid="+appVersion.getId()
							 +"&aid="+appVersion.getAppId()
							 +"&error=error2";
				} 
				downloadLink = request.getContextPath()+"/statics/uploadfiles/"+apkFileName;
				apkLocPath = path+File.separator+apkFileName;
			}else{
				return "redirect:/dev/flatform/app/appversionmodify?vid="+appVersion.getId()
						 +"&aid="+appVersion.getAppId()
						 +"&error=error3";
			}
		}
		appVersion.setModifyBy(((DevUser)session.getAttribute("devUserSession")).getId());
		appVersion.setModifyDate(new Date());
		appVersion.setDownloadLink(downloadLink);
		appVersion.setApkLocPath(apkLocPath);
		appVersion.setApkFileName(apkFileName);
		try {
			if(appVersionService.modify(appVersion)){
				return "redirect:/dev/flatform/app/list";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "developer/appversionmodify";
	}
	
	@RequestMapping("/delfile.json")
	@ResponseBody
	public Object delfileJson(@RequestParam("id")String id,@RequestParam("flag")String flag){
		String data = "failed";
		if(flag.equals("logo")){
			if(appInfoService.updateLogo(id)){
				data="success";
			}
		}else if(flag.equals("apk")){
			if(appVersionService.updateAPK(id)){
				data="success";
			}
		}
		return JSON.toJSONString(data);
	}
	
	@RequestMapping("/appinfomodify")
	public String appinfomodify(@RequestParam("id")String id,Model model){
		AppInfo appInfo = appInfoService.getAppInfo(Integer.parseInt(id));
		model.addAttribute("appInfo",appInfo);
		return "developer/appinfomodify";
	}
	
	@RequestMapping("/appinfomodifysave")
	public String appinfomodifysave(AppInfo appInfo,HttpServletRequest request,HttpSession session,
				@RequestParam(value="attach",required=false)MultipartFile attach){
		String logoPicPath =  null;
		String logoLocPath =  null;
		if(!attach.isEmpty()){
			String path = request.getSession().getServletContext().getRealPath("statics"+java.io.File.separator+"uploadfiles");
			String oldFileName = attach.getOriginalFilename();//原文件名
			String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
			int filesize = 500000;
			if(attach.getSize() > filesize){//上传大小不得超过 50k
				request.setAttribute("fileUploadError", "* 上传文件过大！");
				return "developer/appinfoadd";
            }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") 
			   ||prefix.equalsIgnoreCase("jepg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式
				 String fileName = appInfo.getAPKName() + ".jpg";//上传LOGO图片命名:apk名称.apk
				 File targetFile = new File(path,fileName);
				 if(!targetFile.exists()){
					 targetFile.mkdirs();
				 }
				 try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					request.setAttribute("fileUploadError", " * 上传失败！");
					return "developer/appinfoadd";
				} 
				 logoPicPath = request.getContextPath()+"/statics/uploadfiles/"+fileName;
				 appInfo.setLogoPicPath(logoPicPath);
				 logoLocPath = path+File.separator+fileName;
				 appInfo.setLogoLocPath(logoLocPath);
			}else{
				request.setAttribute("fileUploadError", "* 上传文件格式不正确！");
				return "developer/appinfoadd";
			}
		}
		appInfo.setModifyBy(((DevUser)session.getAttribute("devUserSession")).getId());
		appInfo.setModifyDate(new Date());
		appInfo.setUpdateDate(new Date());
		appInfo.setDevId(((DevUser)session.getAttribute("devUserSession")).getId());
		appInfo.setStatus(1);
		try {
			if(appInfoService.modify(appInfo)){
				return "redirect:/dev/flatform/app/list";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "developer/appinfoadd";
	}
	
	@RequestMapping(value="/appview/{appinfoid}",method=RequestMethod.GET)
	public String appview(@PathVariable("appinfoid")String id,Model model){
		AppInfo appinfo = appInfoService.getAppInfo(Integer.parseInt(id));
		List<AppVersion> appVersionList = appVersionService.getappVersionList(id);
		model.addAttribute("appInfo", appinfo);
		model.addAttribute("appVersionList", appVersionList);
		return "developer/appinfoview";
	}
	
	@RequestMapping(value="/delapp.json")
	@ResponseBody
	public Object delapp(@RequestParam("id")String id){
		appVersionService.delAppId(id);
		if(appInfoService.delId(id)){
			return JSON.toJSONString("true");
		}
		return JSON.toJSONString("false");
	}
	
	@RequestMapping(value="{appId}/sale.json/{saleSwitch}")
	@ResponseBody
	public Object sale(@PathVariable("appId") String id,
			@PathVariable("saleSwitch")String saleSwitch){
		AppInfo appinfo = new AppInfo();
		appinfo.setId(Integer.parseInt(id));
		if("open".equals(saleSwitch)){//上架
			appinfo.setStatus(4);
			appinfo.setOnSaleDate(new Date());
		}else if("close".equals(saleSwitch)){//下架
			appinfo.setStatus(5);
			appinfo.setOffSaleDate(new Date());
		}
		if(appInfoService.modify(appinfo)){
			return JSON.toJSONString("success");
		}
		return JSON.toJSONString("failed");
	}
}
